package com.qingmi.farmer.data.repository.api;

import com.luck.picture.lib.rxbus2.RxBus;
import com.qingmi.farmer.data.UserData;
import com.qingmi.farmer.data.model.UserInfo;
import com.wjjun.base.data.net.HTTPSService;
import com.wjjun.base.data.preference.UserPreference;
import com.qingmi.farmer.data.request.LoginByCodeReq;
import com.qingmi.farmer.data.request.LoginReq;
import com.qingmi.farmer.data.response.LoginRes;
import com.qingmi.farmer.event.UserLoginChangeEvent;
import com.wjjun.basemvpvm.data.net.HttpApiManager;
import com.wjjun.basemvpvm.data.net.filter.BaseResponseFilter;
import com.wjjun.basemvpvm.data.repository.BaseApiRepository;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * 用户相关的数据仓库
 * author Wjjun
 * Created 2018/3/20.
 */

public class UserApiRepository extends BaseApiRepository {

    private UserPreference userPreference;
    private UserData userData;

    @Inject
    public UserApiRepository(HttpApiManager httpApiManager,
                             BaseResponseFilter baseResponseFilter, UserPreference userPreference,
                             UserData userData) {
        super(httpApiManager, baseResponseFilter);
        this.userPreference = userPreference;
        this.userData = userData;
    }

    /**
     * 登录
     */
    public Observable<UserInfo> login(LoginReq req) {
        return res2Entity(httpApiManager.getService(HTTPSService.class).login(req, userPreference.getUmengToken()).doOnNext(new Consumer<LoginRes>() {
            @Override
            public void accept(LoginRes loginRes) {
                if (loginRes.isSuccess() && loginRes.getData() != null) {
                    UserInfo userInfo = loginRes.getData();

                    userPreference.setToken(userInfo.getToken());

                    userData.setUserInfo(userInfo);
                    userData.notifyDataChange(UserApiRepository.class);

                    RxBus.getDefault().post(new UserLoginChangeEvent());
                }
            }
        }));
    }

    /**
     * 登录
     */
    public Observable<UserInfo> loginByCode(LoginByCodeReq req) {
        return res2Entity(httpApiManager.getService(HTTPSService.class).loginByCode(req, userPreference.getUmengToken()).doOnNext(new Consumer<LoginRes>() {
            @Override
            public void accept(LoginRes loginRes) {
                if (loginRes.isSuccess() && loginRes.getData() != null) {
                    UserInfo userInfo = loginRes.getData();

                    userPreference.setToken(userInfo.getToken());

                    userData.setUserInfo(userInfo);
                    userData.notifyDataChange(UserApiRepository.class);

                    RxBus.getDefault().post(new UserLoginChangeEvent());
                }
            }
        }));
    }

}




